package com.gxa.jjty.phy.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 配置redis操作数据(key/value)的时候运用的徐磊话格式(string/jdk/jackson2)
 *
 * @ClassName RedisConfig
 * @Author: ws
 * @date 2021/11/25 10:48
 */
@Configuration
public class RedisConfig {

    /**
     * RedisTemplate<K,V> 操作redis的主题对象，序列化的配置要在RedisTemplate中体现
     * K: kye的泛型类型，用String 来表示
     * V: value的泛型类型，为了把5种数据类型都概括进来，所用要用Object
     *
     * @param factory RedisConnectionFactory: spring从当前配置中加载pool连接池配置和redis基础连接配置项生存的
     * @return
     * @Bean 为了service种调用redis的操作类，提前通过@Bean的方式准备好
     */
    @Bean
    public RedisTemplate<String, Object> getRedisTemplate(RedisConnectionFactory factory) {

        // 实例化一个RedisTemplate(操作redis中不同数据类型的CRUD)
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 指定连接
        template.setConnectionFactory(factory);

        // 指定两种序列化器: String序列化器(用在key中)/jackson2序列化器(用在value)

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        // ObjectMapper 是jackson 转换json格式的核心类型
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        jackson2JsonRedisSerializer.setObjectMapper(om);


        StringRedisSerializer stringRedisSerializer = new
                StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        // user[name=张三] -> {"user":{"name":"张三"}}
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;

    }

}
